<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/21
 * Time: 17:00
 */

namespace App\Http\Controllers\Admin;

use App\Model\Banner;
use App\Model\Branch;
use App\Model\DirectWeighting;
use App\Model\ExceedShop;
use App\Model\Members;
use App\Model\Notice;
use App\Model\PartnerRecord;
use App\Model\Permissions;
use App\Model\RecordBonus;
use App\Model\RecordTransaction;
use App\Model\SetBonus;
use App\Model\SetPartner;
use App\Model\SetQuality;
use App\Model\SetRead;
use App\Model\SetRebate;
use App\Model\ShopOrder;
use Illuminate\Http\Request;
use App\Model\User;
use App\Model\MembersLevel;
use App\Model\MicroMall;
use App\Model\Poundage;
use App\Model\StraightShopp;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Session;
use Log;

class    SystemController extends BaseController
{
    /**
     * 系统用户
     */
    public function indexPage()
    {
        return view('Admin/system');
    }
    /**
     * 添加系统用户
     */
    public function addUserPage()
    {
        return view('Admin/addUser');
    }

    /*
     * 日志列表
     */
    public function logs()
    {
        $hostdir = storage_path().'/logs';
        $filesnames = scandir($hostdir);
        $filesnames = array_slice($filesnames,3);
        $path = array();
        foreach($filesnames as $k=>$name){
            $file_path = $hostdir."/".$name;
            if(file_exists($file_path)){
                $fp = fopen($file_path,'r');
                $str = fread($fp,filesize($file_path));
                $str = str_replace("\r\n","<br />",$str);
                $pattern = "/\[\w+\S+\s+\S+\s+\w+\.INFO:.*`/";
                rsort($path);
                preg_match_all($pattern, $str, $path[$k]);
                fclose($fp);
            }
        }
        return view('Admin.logs',compact('path',$path));
    }

    /**
     * 获取用户数据
     * @param Request $request
     * @return array|string
     */
    public function getUser(Request $request)
    {
        if($request->ajax()){
            $dataUser = $request->all();
            Switch  ($dataUser['class']){
                case 'select': //查询
                    $user = User::where('status', '>', 0)->select('id','name','user_name','emil','phone','login_time','ip','position','is_branch','status')->get()->toArray();
                    if($user){
                        return ['code'=>1,'data'=>$user];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'find'; //获取用户是否注册
                    $user = User::where(['name'=>$dataUser['name']])->count();
                    if (empty($user)) {
                        return ['code'=>1,'data'=>'可以注册'];
                    } else {
                        return ['code'=>0,'data'=>'已经被注册'];
                    }
                    break;
                case 'add';
                    $data = $request->all();
                    $user = User::where('id',$data['users']['id'])->first();
                    if(!$user){
                        $user = new User();
                        $countUser = User::where(['name'=>$data['users']['name']])->count();
                        if($countUser)
                            return ['code'=>0,'data'=>'已经被注册'];
                    }
                    $permissions_id = '';
                    foreach ($data['permissions'] as $val){
                        foreach ($val['children'] as $child){
                            if($child['status'] == 'true'){
                                $permissions_id = empty($permissions_id)?$child['id']:$permissions_id.','.$child['id'];
                            }
                        }
                    }
                    $user->name = $data['users']['name'];
                    $user->user_name = $data['users']['user_name'];
                    $user->emil = $data['users']['emil'];
                    $user->phone = $data['users']['phone'];
                    if (!$user) {
                        $user->password = RANDOM($data['users']['password'],RANDOM());
                        $user->password = md5($data['users']['password'].'baoli');
                    }
                    $user->position = $data['users']['position'];
                    $user->is_branch = $data['users']['is_branch'];
                    $user->permissions_id = $permissions_id;
                    $user->note = $data['users']['note'];
                    if(!$user){
                        $user->sign_in = time();
                    }
                    $rico = $user->save();
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'delete': //删除
                    $user = User::where('id',$dataUser['id'])->first();
                    $user->status = -1;
                    $rico = $user->save();
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
                case 'edit': //编辑
                    $user = User::where('id',$dataUser['id'])->first();
                    $user['permissions_id'] = explode(',', $user['permissions_id']);
                    if($user){
                        return ['code'=>1,'data'=>$user];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     * 分公司
     */
    public function branchPage()
    {
       // Log::info(Auth::user()->name.'查看分公司列表`');
        return view('Admin/branch');
    }
    /**
     * 添加分公司页面
     */
    public function addBranchPage()
    {
        return view('Admin/addBranch');
    }
    /**
     * 获取分公司数据
     * @param Request $request
     * @return array|string
     */
    public function getBranch(Request $request)
    {
        if($request->ajax()){
            $class = $request->get('class');
            Switch  ($class){
                case 'select': //查询
                    if ($request->get('id')) {
                        $branch = Branch::where('id',$request->get('id'))->first();
                    } else {
                        $branch = Branch::where('status',1)->get()->toArray();
                    }
                    if($branch){
                        return ['code'=>1,'data'=>$branch];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'delete': //删除
                    $user = Branch::where('id',$request->get('id'))->first();
                    $user->status = -1;
                    $rico = $user->save();
                    if($rico){
                        Log::info(Auth::user()->name.'删除分公司`');
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }

        }
    }
    /**
     * 分公司 添加 or 修改
     * @param Request $request
     * @return array
     */
    public function addBranch(Request $request)
    {
        if($request->ajax()){
            $user = Branch::where('id',$request->get('id'))->first();
            if(!$user)
                $user = new Branch();
            $user->name = $request->get('name');
            $user->phone = $request->get('phone');
            $user->email = $request->get('email');
            $user->province = $request->get('province');
            $user->city = $request->get('city');
            $user->district = $request->get('district');
            $user->address = $request->get('address');
            $user->note = $request->get('note');
            if($request->get('id')){
                $user->createtime = time();
            }
            $rico = $user->save();
            if($rico){
                Log::info(Auth::user()->name.'添加分公司`');
                return ['code'=>1,'data'=>'设置成功'];
            } else {
                return ['code'=>0,'data'=>'设置失败'];
            }
        }
    }

    /**
     * 权限列表
     */
    public function permissions()
    {
        return view('Admin/permissions');
    }

    /**
     * 获取
     * @param Request $request
     * @return array
     */
    public function getPermissions(Request $request)
    {
        if($request->ajax()){
            $class = $request->get('class');
            Switch  ($class){
                case 'select': //查询
                    $userId = $request->get('user_id');
                    $permissionsId = '';
                    if($userId){
                        $user = User::where('id',$userId)->first();
                        $permissionsId = explode(',', $user['permissions_id']);
                    }
                    $data = Permissions::get()->toArray();
                    $permissions = array();
                    foreach ($data as $key => $val){
                        $data[$key]['status'] = false;
                        if($permissionsId){
                            foreach ($permissionsId as $k=>$v){
                                if ($val['id'] == $v) {
                                    $data[$key]['status'] = true;
                                }
                            }
                        }
                        if ($val['pid'] != 0) {
                            $permissions[$val['pid']]['children'][] = $data[$key];
                        } else {
                            $permissions[$val['id']]['name'] = $val['name'];
                        }
                    }
                    if($permissions){
                        return ['code'=>1,'data'=>$permissions];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'delete': //删除
                    $user = Branch::where('id',$request->get('id'))->first();
                    $user->status = 0;
                    $rico = $user->save();
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
                case '':

                    break;
            }
        }
    }

    /**
     * 系统设置页面
     */
    public function set()
    {
        return view('Admin/set');
    }
    /**
     *抢购商城设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function setQuality(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $res = SetQuality::get(); //超级商城等级
                    if($res){
                        return ['code'=>1,'data'=>$res];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if(!$data['setQuality']['level_name']){
                        return ['code' => 0, 'data' => '名称不能为空'];
                    }
//                    if(!$data['setQuality']['reword']){
//                        return ['code' => 0, 'data' => '奖励占比'];
//                    }
//                    if(!$data['setQuality']['flat']){
//                        return ['code' => 0, 'data' => '平级占比'];
//                    }
//                    if(!$data['setQuality']['team_count']){
//                        return ['code' => 0, 'data' => '团队业绩不能为空'];
//                    }
//                    if(!isset($data['setQuality']['small_team_count'])){
//                        return ['code' => 0, 'data' => '小区团队业绩不能为空'];
//                    }
//                    if(is_null($data['setQuality']['big_team'])){
//                        return ['code' => 0, 'data' => '大区团队数量不能为空'];
//                    }
//                    if(is_null($data['setQuality']['big_team_count'])){
//                        return ['code' => 0, 'data' => '大区团队业绩不能为空'];
//                    }
                    if ($data['setQuality']['id']) { //修改
//                        $data['shop']['type'] = 0;
                        $rico = SetQuality::where('id',$data['setQuality']['id'])->update($data['setQuality']);
                    } else {
                        $rico = SetQuality::create($data['setQuality']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                case 'changer'://平级奖励开关
                    if (!empty($data['id'])){
                        $res = SetQuality::where('id',$data['id'])->update(['changer' => $data['changer']]);
                        if ($res){
                            return ['code' => 1,'data' => '操作成功'];
                        } else {
                            return ['code' => 0,'data' => '操作失败'];
                        }
                    } else {
                        return ['code' => 0,'data' => '参数错误'];
                    }
                    break;
                case 'delete':
                    $memberModel = new ExceedShop();
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     *抢购商城设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function setBonus(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $res = SetBonus::get(); //超级商城等级
                    if($res){
                        return ['code'=>1,'data'=>$res];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if(!$data['setBonus']['level_name']){
                        return ['code' => 0, 'data' => '名称不能为空'];
                    }
                    if(is_null($data['setBonus']['reword'])){
                        return ['code' => 0, 'data' => '奖励份额不能为空'];
                    }
//                    if(!$data['setQuality']['flat']){
//                        return ['code' => 0, 'data' => '平级占比'];
//                    }
                    if(is_null($data['setBonus']['team_count'])){
                        return ['code' => 0, 'data' => '团队业绩不能为空'];
                    }
                    if(is_null($data['setBonus']['small_team_count'])){
                        return ['code' => 0, 'data' => '小区团队业绩不能为空'];
                    }
                    if(is_null($data['setBonus']['big_team'])){
                        return ['code' => 0, 'data' => '大区团队业绩不能为空'];
                    }
                    if(is_null($data['setBonus']['pre_team_count'])){
                        return ['code' => 0, 'data' => '额外份额不能为空'];
                    }
                    if ($data['setBonus']['id']) { //修改
//                        $data['shop']['type'] = 0;
                        $rico = SetBonus::where('id',$data['setBonus']['id'])->update($data['setBonus']);
                    } else {
                        $rico = SetBonus::create($data['setBonus']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                case 'changer'://平级奖励开关
                    if (!empty($data['id'])){
                        $res = SetQuality::where('id',$data['id'])->update(['changer' => $data['changer']]);
                        if ($res){
                            return ['code' => 1,'data' => '操作成功'];
                        } else {
                            return ['code' => 0,'data' => '操作失败'];
                        }
                    } else {
                        return ['code' => 0,'data' => '参数错误'];
                    }
                    break;
                case 'delete':
                    $memberModel = new ExceedShop();
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     * 会员等级 设置
     */
    public function memberLevel(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $level = MembersLevel::orderBy('conditions', 'desc')->get()->toArray();
                    if($level){
                        return ['code'=>1,'data'=>$level];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if ($data['level']['id']) { //修改
                        $rico = MembersLevel::where('id',$data['level']['id'])->update($data['level']);
                    } else {
                        if(!$data['level']['level_name']){
                            return ['code' => 0, 'data'=>'等级名称不能为空'];
                        }
                        if(!$data['level']['conditions']){
                            return ['code' => 0, 'data'=>'条件不能为空'];
                        }
                        if(!$data['level']['credit3']){
                            return ['code' => 0, 'data'=>'复投币不能为空'];
                        }
                        if(!$data['level']['day_caps']){
                            return ['code' => 0, 'data'=>'日封顶不能为空'];
                        }
                        $data['level']['createtime'] = time();
                        $rico = MembersLevel::create($data['level']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':

                    break;
                case 'delete':
                    $memberModel = new Members();
                    $count = $memberModel->count_member(['level'=>$data['level']['id']]);
                    if ( $count > 0 ) {
                        return ['code'=>0,'data'=>'该会员等级下来有会员不能删除'];
                    }
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }

    /**
     * 微商城设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function microMall(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $micro = MicroMall::get()->toArray(); //微商城等级
                    if($micro){
                        return ['code'=>1,'data'=>$micro];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if(!$data['microMall']['level_name']){
                        return ['code' => 0, 'data' => '等级名称不能为空'];
                    }
                    if(is_null($data['microMall']['direct'])){
                        return ['code' => 0, 'data' => '直推人奖励占比不能为空'];
                    }
//                    if(!$data['microMall']['discount']){
//                        return ['code' => 0, 'data' => '折扣不能为空'];
//                    }
                    if ($data['microMall']['id']) { //修改
                        $rico = MicroMall::where('id',$data['microMall']['id'])->update($data['microMall']);
                    } else {
                        $rico = MicroMall::create($data['microMall']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                    break;
                case 'delete':
                    $memberModel = new MicroMall();
                    $count = $memberModel->count_member(['level'=>$data['level']['id']]);
                    if ( $count > 0 ) {
                        return ['code'=>0,'data'=>'该会员等级下来有会员不能删除'];
                    }
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     * 超级微商城设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function exceedShop(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $micro = ExceedShop::get(); //超级商城等级
                    if($micro){
                        return ['code'=>1,'data'=>$micro];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if(!$data['shop']['vip_name']){
                        return ['code' => 0, 'data' => '等级名称不能为空'];
                    }
                    if(!isset($data['shop']['vip'])){
                        return ['code' => 0, 'data' => '直推占比不能为空'];
                    }
                    if(!isset($data['shop']['tutor'])){
                        return ['code' => 0, 'data' => '平级占比不能为空'];
                    }

                    if ($data['shop']['id']) { //修改
//                        $data['shop']['type'] = 0;
                        $rico = ExceedShop::where('id',$data['shop']['id'])->update($data['shop']);
                    } else {
                        $rico = ExceedShop::create($data['shop']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                    break;
                case 'delete':
                    $memberModel = new ExceedShop();
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     * 系统设置
     * @param Request $request
     * @return array
     */
    public function system(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $system = Poundage::first()->toArray();
                    $system['withdrawal_day'] = explode(',',$system['withdrawal_day']);
                    if($system){
                        return ['code'=>1,'data'=>$system];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    $pattern = '/^1[3456789]d{9}$/';
                    if(empty($data['system']['day_times'])){
                        return ['code'=>0,'data'=>'充值热线有误'];
                    }
                    if(empty($data['system']['day_probability'])){
                        return ['code'=>0,'data'=>'售后热线有误'];
                    }
                    if ($data['system']['id']) { //修改
                        $rico = Poundage::where('id',$data['system']['id'])->update($data['system']);
                    } else {
                        $rico = Poundage::create($data['system']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;

            }
        }
    }
    /**
     * 阅读设置
     * @param Request $request
     * @return array|void
     */
    public function setRead( Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $set = SetRead::get()->toArray();
                    if($set){
                        return ['code'=>1,'data'=>$set];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if ($data['set']['id']) { //修改
                        $rico = SetRead::where('id',$data['set']['id'])->update($data['set']);
                    } else {
                        $rico = Poundage::create($data['set']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;

            }
        }
    }
    /**
     * 直商城设置
     * @param Request $request
     * @return array
     */
    public function shop(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $shop = StraightShopp::first()->toArray();
                    if($shop){
                        return ['code'=>1,'data'=>$shop];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if ($data['shop']['id']) { //修改
                        $rico = StraightShopp::where('id',$data['shop']['id'])->update($data['shop']);
                    } else {
                        $rico = StraightShopp::create($data['shop']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;

            }
        }
    }

    /**
     * 个人中心
     */
    public function center()
    {
        return view('Admin.center');
    }
    public function centerSet(Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']) {
                case 'select':
                   $adminUser = Auth::user();
//                    $adminUser = session('admin_user');
                    $user = User::where(['id'=>$adminUser->id])->first();
                    if ($user) {
                        return ['code' => 1, 'data' => $user];
                    } else {
                        return ['code' => 0, 'data' => '没有数据'];
                    }
                    break;
                case 'edit':
                    $rico = User::where('id',$data['user']['id'])->update($data['user']);
                    if ($rico) {
                        session('admin_user',$data['user']);
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                    break;
                case 'editPas':
                    $userData = Auth::user();
                    if($data['passwords']['newPassword'] != $data['passwords']['confirmPassword']){
                        return ['code' => '0' , 'data' => '两次密码不一致'];
                    }else {
                        $data['passwords']['password'] = bcrypt($data['passwords']['newPassword']);
                    }

                    $rico = User::where('id',$userData->id)->update(array_only($data['passwords'],['password']));
//                    $rico = User::where('id',$userData->id)->update(array_only($data['passwords']),['password']);

                    if ($rico) {
                        Auth::logout();
                        return ['code' => 1, 'data' => '修改成功，重新登录！'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                    break;
            }
        }


    }
    /**
     * 安全退出
     */
    public function LogOut()
    {
       // Session::put('admin_user',null);
        \Auth::guard('admin')->logout();
        return redirect('/admin/login/login')->withErrors('退出成功！');
    }
    
    /**
     * 系统公告
     */
    public function notice(){
        return view('Admin.notice.index');
    }
    /**
     * 公告添加页面
     */
    public function addNotice(){
        return view('Admin.notice.addNotice');
    }

    /**
     * 系统公告设置
     * @param Request $request
     * @return array
     */

    public function setNotice( Request $request ){
        $data = $request->all();
        $noticeModel = new Notice();
        switch ($data['class']){
            case 'select'://列出所有公告
                $notice = $noticeModel->getAll();
                if ( $notice ){
                    return ['code' => 1,'data' => $notice];
                } else {
                    return ['code' => 0,'data' => '暂无公告'];
                }
                break;
            case 'find'://查询单条公告
                $notice = $noticeModel->getOne($data['id']);
                if ( $notice ){
                    return ['code' => 1,'data' => $notice];
                } else {
                    return ['code' => 0,'data' => '参数错误'];
                }
                break;
            case 'add'://添加公告
                if (!$data['notice']['notice_name']){
                    return ['code' => 0,'data' => '公告名不能为空'];
                }
                if (!$data['notice']['content']){
                    return ['code' => 0,'data' => '公告内容不能为空'];
                }
                if (!$data['time']){
                    return ['code' => 0,'data' => '请设置起始时间'];
                }
                $data['notice']['release_time'] = $data['time'][0];
                $data['notice']['deadline'] = $data['time'][1];
                $res = Notice::create($data['notice']);
                if ($res){
                    return ['code' => 1,'data' => '发送成功'];
                } else {
                    return ['code' => 0,'data' => '发送失败'];
                }
                break;
            case 'edit'://修改公告内容
                $notice = $noticeModel->getOne($data['id']);
                if ($notice['is_publish'] == 1){
                    return ['code' => 0,'data' => '请先取消公告后再进行修改'];
                }
                if (!$data['notice']['notice_name']){
                    return ['code' => 0,'data' => '公告名不能为空'];
                }
                if (!$data['notice']['content']){
                    return ['code' => 0,'data' => '公告内容不能为空'];
                }
                if (!$data['time']){
                    return ['code' => 0,'data' => '请设置起始时间'];
                }
                $data['notice']['is_publish'] = 1;
                $data['notice']['release_time'] = $data['time'][0];
                $data['notice']['deadline'] = $data['time'][1];

                $res = Notice::where('id',$data['id'])->update($data['notice']);
                if ($res){
                    return ['code' => 1,'data' => '修改成功'];
                } else {
                    return ['code' => 0,'data' => '修改失败'];
                }
                break;
            case 'delete':
                $res = Notice::where('id',$data['id'])->update(['is_publish' => -1]);
                if ($res){
                    return ['code' => 1,'data' =>'取消成功'];
                } else {
                    return ['code' => 0,'data' => '参数错误'];
                }
                break;

        }
    }
    /**
     * 直推加权设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function weighting (Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $micro = DirectWeighting::get(); //超级商城等级
                    if($micro){
                        return ['code'=>1,'data'=>$micro];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
//                    if(empty($data['shop']['start'])){
//                        return ['code' => 0, 'data' => '参与次数起始范围不能为空'];
//                    }
//                    if(empty($data['shop']['end'])){
//                        return ['code' => 0, 'data' => '参与次数结束范围不能为空'];
//                    }
//                    if(empty($data['shop']['rebate'])){
//                        return ['code' => 0, 'data' => '返利不能为空'];
//                    }
                    if ($data['shop']['id']) { //修改
//                        $data['shop']['type'] = 0;
                        $rico = DirectWeighting::where('id',$data['shop']['id'])->update(array_only($data['shop'],['name','bonus','bill']));
                    } else {
                        $rico = DirectWeighting::create($data['shop']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                    break;
                case 'delete':
                    $memberModel = new ExceedShop();
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     * 抢购商城积分红包返利设置
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function bonusPoints (Request $request)
    {
        if($request->ajax()){
            $data = $request->all();
            switch ($data['class']){
                case 'select':
                    $micro = SetRebate::get(); //超级商城等级
                    if($micro){
                        return ['code'=>1,'data'=>$micro];
                    } else {
                        return ['code'=>0,'data'=>'没有数据'];
                    }
                    break;
                case 'add':
                    if(empty($data['shop']['points_balance'])){
                        return ['code' => 0, 'data' => '积分余额不能为空'];
                    }
                    if(empty($data['shop']['proportion'])){
                        return ['code' => 0, 'data' => '积分红包占比不能为空'];
                    }
                    if ($data['shop']['id']) { //修改
//                        $data['shop']['type'] = 0;
                        $rico = SetRebate::where('id',$data['shop']['id'])->update(array_only($data['shop'],['points_balance','proportion']));
                    } else {
                        $rico = SetRebate::create($data['shop']);
                    }
                    if($rico){
                        return ['code'=>1,'data'=>'设置成功'];
                    } else {
                        return ['code'=>0,'data'=>'设置失败'];
                    }
                    break;
                case 'find':
                    break;
                case 'delete':
                    $memberModel = new ExceedShop();
                    $rico = $memberModel->delete($data['level']['id']);
                    if($rico){
                        return ['code'=>1,'data'=>'删除成功'];
                    } else {
                        return ['code'=>0,'data'=>'删除失败'];
                    }
                    break;
            }
        }
    }
    /**
     *轮播列表
     */
    public function bannerIndex()
    {
        return view('Admin/banner/index');
    }

    /**
     * 添加轮播
     */

    public function addBanner()
    {
        return view('Admin/banner/add');
    }


    /**
     * 轮播管理
     * @param Request $request
     * @return array
     */
    public function banner(Request $request) {
        $data = $request->all();
        $BannerModel = new Banner();
        switch ($data['class']){
            case 'select': //轮播列表
                $BannerData = $BannerModel->get_banner();
                foreach ($BannerData as $k => $v){
                    $BannerData[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }

                if($BannerData){
                    return ['code' => 1, 'data'=>$BannerData];
                }
                break;

            case 'add': //添加轮播
                if(!$data['banner']['banner_title']){
                    return ['code' =>0,'data'=>'请填写轮播标题'];
                }
                if(!$data['banner']['banner_img']){
                    return ['code' =>0,'data'=>'请上传轮播图'];
                }
                if(!empty($data['banner']['id'])){
                    $data['banner']['create_time'] = strtotime($data['banner']['create_time']);
                    $res = $BannerModel->edit_banner($data['banner'],$data['banner']['id']);
                }else{
                    $data['banner']['create_time'] = time();
                    $res = $BannerModel->add_banner($data['banner']);
                }
                if($res){
                    return ['code' => 1,'data' => '操作成功'];
                } else {
                    return ['code' => 0, 'data' => '操作失败'];
                }

                break;
            case 'find':
                $FindData = $BannerModel->find_banner($data['id']);
                if($FindData){
                    return ['code'=>1,'data'=>$FindData];
                }
                break;
            case 'delete':
                $res = $BannerModel->delete_banner($data['id']);
                if($res){
                    return ['code' => 1, 'data' =>'删除成功'];
                } else {
                    return ['code' => 0, 'data' => '删除失败'];
                }
                break;
        }
    }

    //发放业绩奖励
    public function savePerformance()
    {
        $memberData = Members::where('credit4','>',0)->where('level','>',0)->get()->toArray();
        foreach ($memberData as $K => $v){
            $money = $v['credit4'];
            $v['credit2'] = $v['credit4'] + $v['credit2'];
            $v['achievement'] = 0;
            $v['credit4'] = 0;
            $recommendMoney = ['money' => $money,'redelivery' => 0];
            Members::where('uid',$v['uid'])->update($v);
            //添加记录
            $this->addOrder($v['uid'],$money,5,'每月业绩奖分红',$recommendMoney,0,'');
        }
    }

    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null, $money = null, $type = null, $explain = '', $manageMoney = array(), $company_id = null, $ordersn = '')
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        //交易记录表
        $order_uid = ShopOrder::where('ordersn', $ordersn)->value('uid');
        $userName = Members::where('uid', $order_uid)->value('user_name');
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $money,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain . '：' . $manageMoney['money'],
//            'remark' => $explain . '：' . $money. '，参与积分来源：用户' . $userName . '参与抢购' . ')',
            'time' => time(),
            'type' => 1,
            'company_id' => $company_id,
        ];
        $RecordBonus->add_bonus($bonusData);
    }

    /**
     * 添加平台合伙人分红
     */
    public function setShareholders()
    {
        return view('Admin.setShareholders');
    }

    /**
     * 平台合伙人设置
     */
    public function shareholders(Request $request)
    {
        $data = $request->all();
        switch ($data['class']) {
            //代理合伙人列表
            case 'select':
                //关键字
                $keyword = empty($data['keyword'])?0:$data['keyword'];
                $applyData = SetPartner::select();
                //状态
                if(isset($keyword['status'])){
                    $applyData = $applyData->where('status',$keyword['status']);
                }
                //关键字
                if(!empty($keyword['keyword'])){
                    $applyData = $applyData->where('name','like','%'.$keyword['keyword'].'%')->orWhere('user_name','like','%'.$keyword['keyword'].'%');
                }
                //分页
                $applyData = $applyData->orderBy('id', 'desc')
                    ->paginate(15);
                if($applyData){
                    return ['code' => 1 , 'data' => $applyData];
                } else {
                    return ['code' => 0 , 'data' => '暂无数据'];
                }
                break;
            //代理合伙人是否存在系统
            case 'find_member': //删除
                if($data['name']){
                    $members = Members::where('name',$data['name'])->select('name','user_name')->first();
                    if($members){
                        return ['code' => 1 , 'data' => $members];
                    }else{
                        return ['code' => 0 , 'data' => '此系统暂无该会员'];
                    }
                }
                break;
            //代理合伙人申请
            case 'add':

                if(empty($data['name'])){
                        return ['code' => 0, 'data' => '合伙人账号不能为空'];
                    }
                if(empty($data['user_name'])){
                    return ['code' => 0, 'data' => '合伙人姓名不能为空'];
                }
                $members = SetPartner::where(['name'=>$data['name']])->first();
                if($members){
                    return ['code' => 0 , 'data' => '此会员已是合伙人'];
                }
                $adminUser = Auth::user();
                $data['information']['verifier'] = $adminUser->user_name;
                $data['information']['status'] = 1;
                $data['information']['name'] = $data['name'];
                $data['information']['user_name'] = $data['user_name'];
                $userRoic = SetPartner::create($data['information']);
                if($userRoic){
                    return ['code' => 1, 'data' => '添加成功'];
                } else {
                    return ['code' => 0, 'data' => '添加失败'];
                }

                break;
            //代理合伙人编辑
            case 'edit':
                if ($data['id']) {
                    if(empty($data['name'])){
                        return ['code' => 0, 'data' => '合伙人账号不能为空'];
                    }
                    if(empty($data['user_name'])){
                        return ['code' => 0, 'data' => '合伙人姓名不能为空'];
                    }
//                    $members = SetPartner::where(['name'=>$data['name']])->first();
//                    if($members){
//                        return ['code' => 0 , 'data' => '此会员已是该代理下合伙人'];
//                    }
                    $adminUser = Auth::user();
                    $data['information']['verifier'] = $adminUser->user_name;
                    $data['information']['status'] = $data['status'];
                    $data['information']['name'] = $data['name'];
                    $data['information']['user_name'] = $data['user_name'];
                    $apply = SetPartner::where('id',$data['id'])->update(array_only($data,['status','verifier','name','user_name']));
                    if ($apply) {
                        return ['code' => 1 , 'data' => '编辑成功'];
                    } else {
                        return ['code' => 0,  'data' => '编辑失败'];
                    }
                }
                break;
            case 'details':
                if (empty($data['a_id'])){
                    return ['code' => 0,'data' => '请选择分红对象'];
                }
                foreach ($data['a_id'] as $k => $v){
                    if (!is_numeric($v)){
                        unset($data['a_id'][$k]);
                    }
                }
                if (!empty($data['money'])){

                    //合伙人人数
                    $member_count = SetRebate::where(['status' => 1,'type' => 1])->whereIn('a_id',$data['a_id'])->count();
                    //服务组人数
                    $group_count = SetRebate::where(['status' => 1,'type' => 2])->whereIn('a_id',$data['a_id'])->count();
                    if ($data['enctype'] == 1){
                        //总分红金额
                        $total_money = RETAIN_TWO($member_count * $data['money']);
                        $count = $member_count;
                    } else if ($data['enctype'] == 2){
                        //总分红金额
                        $total_money = RETAIN_TWO($group_count * $data['money']);
                        $count = $group_count;
                    } else {
                        //总分红金额
                        $total_money = RETAIN_TWO(($member_count + $group_count) * $data['money']);
                        $count = $member_count + $group_count;
                    }

                    return ['code' => 1,'count' => $count,'total' => $total_money];
                }
                break;
            case 'calculation'://平台手动分红计算
                if (!empty($data['money'])){
                    //合伙人人数
                    $member_count = SetPartner::where(['status' => 1])->count();
                    //总分红金额
                    $total_money = RETAIN_TWO($member_count * $data['money']);
                    return ['code' => 1,'count' => $member_count,'total' => $total_money];
                }
                break;
            case 'switch'://平台手动分红执行
                if (empty($data['name'])){
                    return ['code' => 0,'data' => '请填写分红备注'];
                }
                if ((!empty($data['money'])) && (!empty($data['total_money']))){
                    $record = [
                        'ordersn' => ORDER_SN(),
                        'money' => $data['money'],
                        'number' => $data['number'],
                        'total_money' => $data['total_money'],
                        'name' => $data['name'],
                        'time' => time()
                    ];
                    DB::beginTransaction();
                    $res = PartnerRecord::create($record);
                    if ($res){
                        //合伙人分红
                        $members = SetPartner::where(['status' => 1])->get()->toArray();
                        foreach ($members as $k => $v){
                            $user = Members::where('name',$v['name'])->first();
                            $re = Members::where('name',$v['name'])->update(['credit2' => $user['credit2'] + $data['money']]);
                            $recommendMoney = ['money' => $data['money'],'redelivery' => 0];
                            $this->addOrder($user['uid'],$data['money'],5,'平台合伙人分红',$recommendMoney,0,$record['ordersn']);
                            if (!$re){
                                DB::rollback();
                                return ['code' => 0,'data' => '分红失败'];
                            }
                        }
                    }

                    DB::commit();
                    return ['code' => 1,'data' => '分红成功'];
                } else {
                    DB::rollback();
                    return ['code' => 0,'data' => '添加记录失败'];
                }
                break;
            case 'submit':
                if (empty($data['name'])){
                    return ['code' => 0,'data' => '请填写分红备注'];
                }
                if ((!empty($data['money'])) && (!empty($data['total_money']))){
                    $record = [
                        'ordersn' => ORDER_SN(),
                        'money' => $data['money'],
                        'number' => $data['number'],
                        'total_money' => $data['total_money'],
                        'name' => $data['name'],
                        'time' => time()
                    ];
                    DB::beginTransaction();
//                    var_dump(1111);
                    $res = PartnerRecord::create($record);
                    if ($res){
                        if ($data['enctype'] == 1){
                            //合伙人分红
                            $members = SetRebate::where(['status' => 1,'type' => 1])->whereIn('a_id',$data['a_id'])->get()->toArray();
                            foreach ($members as $k => $v){
                                $user = Members::where('name',$v['name'])->first();
                                $re = Members::where('name',$v['name'])->update(['credit2' => $user['credit2'] + $data['money']]);
                                $recommendMoney = ['money' => $data['money'],'redelivery' => 0];
                                $this->addOrder($user['id'],$data['money'],5,'合伙人分红',$recommendMoney,0,$record['ordersn']);
                                if (!$re){
                                    DB::rollback();
                                    return ['code' => 0,'data' => '分红失败'];
                                }
                            }
                        } else if ($data['enctype'] == 2){
                            $service = SetRebate::where(['status' => 1,'type' => 2])->whereIn('a_id',$data['a_id'])->get()->toArray();
                            foreach ($service as $k => $v){
                                $user = Members::where('name',$v['name'])->first();
                                $re = Members::where('name',$v['name'])->update(['credit2' => $user['credit2'] + $data['money']]);
                                $recommendMoney = ['money' => $data['money'],'redelivery' => 0];
                                $this->addOrder($user['id'],$data['money'],5,'服务组分红',$recommendMoney,0,$record['ordersn']);
                                if (!$re){
                                    DB::rollback();
                                    return ['code' => 0,'data' => '分红失败'];
                                }
                            }
                        } else {
                            //合伙人分红
                            $members = SetRebate::where(['status' => 1,'type' => 1])->whereIn('a_id',$data['a_id'])->get()->toArray();
                            foreach ($members as $k => $v){
                                $user = Members::where('name',$v['name'])->first();
                                $re = Members::where('name',$v['name'])->update(['credit2' => $user['credit2'] + $data['money']]);
                                $recommendMoney = ['money' => $data['money'],'redelivery' => 0];
                                $this->addOrder($user['uid'],$data['money'],5,'合伙人分红',$recommendMoney,0,$record['ordersn']);
                                if (!$re){
                                    DB::rollback();
                                    return ['code' => 0,'data' => '分红失败'];
                                }
                            }
                            $service = SetRebate::where(['status' => 1,'type' => 2])->whereIn('a_id',$data['a_id'])->get()->toArray();
                            foreach ($service as $k => $v){
                                $user = Members::where('name',$v['name'])->first();
                                $re = Members::where('name',$v['name'])->update(['credit2' => $user['credit2'] + $data['money']]);
                                $recommendMoney = ['money' => $data['money'],'redelivery' => 0];
                                $this->addOrder($user['uid'],$data['money'],5,'服务组分红',$recommendMoney,0,$record['ordersn']);
                                if (!$re){
                                    DB::rollback();
                                    return ['code' => 0,'data' => '分红失败'];
                                }
                            }
                        }

                        DB::commit();
                        return ['code' => 1,'data' => '分红成功'];
                    } else {
                        DB::rollback();
                        return ['code' => 0,'data' => '添加记录失败'];
                    }
                }
                break;



        }
    }
}
